# -*- coding: utf8 -*-
#from django.db import models
from google.appengine.api import users, mail
from google.appengine.ext import db
import atom
import atom.service
import cgi
import datetime
import gdata
import gdata.auth
import gdata.calendar
import gdata.calendar.client
import gdata.calendar.service
import gdata.docs.client
import gdata.docs.service
import gdata.spreadsheet.service
import getopt
import jinja2
import os
import random
import string
import sys
import time
import urllib
import webapp2
from tables import Employee
from tables.Employee import Employee
import datetime
from datetime import date
import cherrypy
from protorpc import messages

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))


personaldomain = "elliweb.fr"

e0 = Employee(name="lyazidi0", firstname="reda0",
              birthday_date = datetime.date(1988, 05, 12), male =True)

e0.put()
e0.save()

#e1 = Employee(name="lyazidi1", firstname="reda1",
#              birthday_date = datetime.date(1988, 05, 12), male =True)
#
#e1.put()
#e1.save()

#class Note(messages.Message):
#    
#    text = messages.StringField(1, required=True)
#    when = messages.IntegerField(2)
#
#note_instance = Note(text=u'Hello GuestBook!',when = int(time.time()))


class Greeting(db.Model):
  """Models an individual Guestbook entry with an author, content, and date."""
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)


def guestbook_key(guestbook_name=None):
  """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
  return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')



class MainPage(webapp2.RequestHandler):
    
    def CR(self): 
        """
        the Carriage Return
        """
        self.response.out.write("""<br/> """)
        
    def writeln(self, mystring):
        return self.response.out.write("""<p> """ + mystring + """</p> """)
    
    def get(self):
        guestbook_name = self.request.get('guestbook_name')
#        greetings_query = Greeting.all().ancestor(
#            guestbook_key(guestbook_name)).order('-date')
#        greetings = greetings_query.fetch(10)
        #BEGIN CONNERIE
        greetings = db.GqlQuery("SELECT * "
                            "FROM Greeting "
                            "WHERE ANCESTOR IS :1 "
                            "ORDER BY date ASC LIMIT 10",
                            guestbook_key(guestbook_name))

        #END CONNERIE
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri, personaldomain)
            url_linktext = """
            <input type="button" name="blogout" value="Logout"/>
            """
        else:
            url = users.create_login_url(self.request.uri, personaldomain)
            url_linktext = """
            <input type="button" name="blogin" value="Login"/>
            """

        template_values = {
            'greetings': greetings,
            'url': url,
            'url_linktext': url_linktext,
        }
        eb = db.GqlQuery("""
            SELECT *
            FROM Employee
            WHERE ANCESTOR IS :1 
        """)
        
        template = jinja_environment.get_template("firstindex.html")
        self.response.out.write(template.render(template_values))
        
            




def GetResourcesWithExponentialBackoff(client):
  """Gets all of the resources for the user authorized on the given client.

  Args:
    client: gdata.docs.client.DocsClient authorized for a user.
  Returns:
    gdata.docs.data.ResourceFeed representing Resources found in the request.
  """ 
  for n in range(0, 5):
    try:
      response = client.GetResources()
      return response
    except gdata.client.RequestError, error:
      computed_time = (2 ** n) + (random.randint(0, 1000) / 1000)
      time.sleep(max(error.headers.get('Retry-After'), computed_time))
    except:
      time.sleep((2 ** n) + (random.randint(0, 1000) / 1000))
  print "There has been an error, the request never succeeded."
  return None


class Guestbook(webapp2.RequestHandler):
  def post(self):
    # We set the same parent key on the 'Greeting' to ensure each greeting is in
    # the same entity group. Queries across the single entity group will be
    # consistent. However, the write rate to a single entity group should
    # be limited to ~1/second.
    guestbook_name = self.request.get('guestbook_name')
    greeting = Greeting(parent=guestbook_key(guestbook_name))

    if users.get_current_user():
      greeting.author = users.get_current_user()

    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))


app = webapp2.WSGIApplication([('/', MainPage),
                               ('/sign', Guestbook)],
                              debug=True)


"""
#How to send a mail
message = mail.EmailMessage(sender="elliweb.fr Support <r.lyazidi@elliweb.fr>",
                            subject="Envoi de Mail via la GAE")

#message.to = "Elie Alam <al_alam_elie@yahoo.fr>"
message.body = """
"""test 1,2 1,2 vous me recevez ?"""
"""

message.send()
"""        
#def GetAuthSubUrl():
#  next = 'elliweb-test.appspot.com'
#  scopes = ['https://www.google.com/calendar/feeds/']
#  secure = False  # set secure=True to request a secure AuthSub token
#  session = True
#  return gdata.gauth.generate_auth_sub_url(next, scopes, secure=secure, session=session)
#
#print '<a href="%s">Login to your Google account</a>' % GetAuthSubUrl()
